package cn.ingenic.glasssync;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baidu.autoupdatesdk.BDAutoUpdateSDK;
import com.baidu.autoupdatesdk.UICheckUpdateCallback;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.sctek.smartglasses.ui.BindHanlangActivity;
import com.sctek.smartglasses.ui.MainActivity;
import com.sctek.smartglasses.utils.UpdateService;
public class WelcomeActivity extends Activity {
	private BluetoothAdapter mAdapter;
        private boolean mFirst = true;
	private final String TAG = "WelcomeActivity";
        private Dialog mDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.welcome_activity);
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		registerReceiver(mBluetoothReceiver, filter);
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		
		new Handler().post(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				checkNewVersion();
			}
		});
		if (mAdapter.isEnabled()){
		    startActivity();
		}
	}


    private final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
	    @Override
		public void onReceive(Context context, Intent intent) {
		    if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
		    int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
						   BluetoothAdapter.ERROR);
		    if (state == BluetoothAdapter.STATE_ON){
			startActivity();
		    }
		}
	    }
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 1 && resultCode == RESULT_CANCELED) {
		    if (mAdapter.isEnabled()){
			startActivity();
		    }
		}
	}

	public DataInputStream Terminal(String command) throws Exception {
		Process process = Runtime.getRuntime().exec("su");
		OutputStream outstream = process.getOutputStream();
		DataOutputStream DOPS = new DataOutputStream(outstream);
		InputStream instream = process.getInputStream();
		DataInputStream DIPS = new DataInputStream(instream);
		String temp = command + "\n";
		DOPS.writeBytes(temp);
		DOPS.flush();
		DOPS.writeBytes("exit\n");
		DOPS.flush();
		process.waitFor();
		return DIPS;
	}

	private void startActivity() {
		
		BDAutoUpdateSDK.uiUpdateAction(this, new MyUICheckUpdateCallback());
		
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
			    DefaultSyncManager mManager=DefaultSyncManager.getDefault();

			    if (!mManager.getLockedAddress().equals("")) {
					Intent intent = new Intent(WelcomeActivity.this,
							MainActivity.class);
					startActivity(intent);
					finish();
				} else {
					Intent intent = new Intent(WelcomeActivity.this,
							BindHanlangActivity.class);
					startActivity(intent);
					finish();
				}

			}
		}, 2000);
	}
	
	private void checkNewVersion() {
		
		PgyUpdateManager.register(this,
				new UpdateManagerListener() {

					@Override
					public void onNoUpdateAvailable() {
						// TODO Auto-generated method stub
						Log.e(TAG, "onNoUpdateAvailable");
					}

					@Override
					public void onUpdateAvailable(String result) {
						// TODO Auto-generated method stub
						Log.e(TAG, result);
						try {
							final AppBean appBean = getAppBeanFromString(result);
							PackageManager pm = getPackageManager();  
							PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);  
							int versionCode = 0;
							versionCode = Integer.parseInt(appBean.getVersionCode());
							if(versionCode  > pi.versionCode) {
								showNewVersionDialog(appBean.getDownloadURL(), appBean.getVersionName());
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						
					}
		});
	}
	
	private void showNewVersionDialog(final String downloadUrl, final String name) {
		
	    AlertDialog.Builder builder = new Builder(WelcomeActivity.this.getApplication());
		builder.setTitle(R.string.new_app_version);
		builder.setMessage(R.string.new_version_comment);
		builder.setPositiveButton(R.string.update_now, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(!isPackageExist(name))
					startDownload(downloadUrl, name);
			}
		});
		
		builder.setNegativeButton(R.string.update_later, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
		
		AlertDialog dialog = builder.create();
		dialog.getWindow().setType(
					WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		
	}
	
	private void startDownload(String url, String name) {
		Intent intent = new Intent(WelcomeActivity.this, UpdateService.class);
		intent.putExtra("url", url);
		intent.putExtra("name", name);
		startService(intent);
		if (mAdapter.isEnabled()){
		    startActivity();
		}
	}
	
	private boolean isPackageExist(String name) {
		File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), name + ".apk");
		if(file.exists()) {
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.fromFile(file),	"application/vnd.android.package-archive");
			startActivityForResult(intent, 1);
			return true;
		}
		return false;
	}
	
	private class MyUICheckUpdateCallback implements UICheckUpdateCallback {

		@Override
		public void onCheckComplete() {
			Log.e(TAG, "baidu update onCheckComplete================");
		}

	}
	
    @Override
	protected void onDestroy() {
	super.onDestroy();
	Log.i(TAG,"onDestroy");
       	    unregisterReceiver(mBluetoothReceiver);
	    PgyUpdateManager.unregister();
    }
    //When the user returns from the Setting , the Bluetooth is off  will exit the application
    @Override
    	protected void onResume() {
    	super.onResume();
    	
    	Locale local = getResources().getConfiguration().locale;
    	
    	if(!local.getLanguage().contains("zh")) {
    		LinearLayout layout = (LinearLayout)findViewById(R.id.welcome_layout);
    		layout.setBackgroundResource(R.drawable.welcome_background_en_low);
    	}
    	if(mFirst){ 
    	    mFirst = false;
    	    return;
    	}
    	if(mAdapter.isEnabled()==false){
    	    Toast.makeText(this, R.string.bluetooth_off,
    			   Toast.LENGTH_SHORT).show();
    	    finish();
    	}
}
}
